import api from '@/services/order/list-management';

const formatList = (list: OrderListManagementApi.ListResponse[]) => {
  const dataSource: OrderListManagementApi.TableItemInfo[] = [];
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    const { orderItemDatas, ...data } = item;
    // 一个订单里至少有一个商品
    if (orderItemDatas && orderItemDatas.length) {
      for (let j = 0; j < orderItemDatas.length; j++) {
        const orderItem = orderItemDatas[j];
        const result = { ...data, ...orderItem, rowSpan: j === 0 ? orderItemDatas.length : 0 };
        dataSource.push(result);
      }
    }
  }
  return dataSource;
};

export type OrderListManagementList = OrderListManagementApi.ListResponse;
export const getFilterList = async () => {
  const res = await api.getFilterList();
  return res.data;
};
export const getList = async (params: OrderListManagementApi.ListParams) => {
  const res = await api.getList<OrderListManagementList>(params);
  const tableData: Requestor.TableFormatedData<OrderListManagementApi.TableItemInfo> = {
    data: formatList(res.listData),
    current: res.page + 1,
    pageSize: res.limit,
    total: res.count,
    success: res.success,
  };

  return tableData;
};
export const getInfo = async (params: OrderListManagementApi.InfoParams) => {
  const res = await api.getInfo<OrderListManagementList>(params);
  return res.data;
};
export const remove = async (params: OrderListManagementApi.DeleteParams) => {
  const data = await api.remove(params);
  return data;
};
export const updateDelivery = async (params: OrderListManagementApi.DeliveryParams) => {
  const data = await api.updateDelivery(params);
  return data;
};
export default {
  getFilterList,
  getList,
  getInfo,
  remove,
  updateDelivery,
};
